package com.lgkj;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lgkj.adapter.MainPagerAdapter;
import com.lgkj.ui.BaseActivity;
import com.lgkj.ui.LoginActivity;
import com.lgkj.ui.WebViewActivity;
import com.lgkj.ui.main.CarFragment;
import com.lgkj.ui.main.MainNearbyFragment;
import com.lgkj.ui.main.MeiDianFragment;
import com.lgkj.ui.main.MineFragment;
import com.lgkj.ui.meitao.HomeFragment;
import com.lgkj.utils.CommonConstant;
import com.lgkj.utils.CommonUtils;
import com.lgkj.utils.HttpUtils;
import com.lgkj.utils.SharedPreferencesUtils;
import com.lgkj.utils.permission.PermissionUtil;
import com.lgkj.view.ScrollableViewPager;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {

    @BindView(R.id.vp_content)
    ScrollableViewPager vpContent;
    @BindView(R.id.rb_homepage)
    RadioButton rbHomepage;
    @BindView(R.id.rb_shop_car)
    RadioButton rbShopCar;
    @BindView(R.id.rb_nearby)
    RadioButton rbNearby;
    @BindView(R.id.rb_mine)
    RadioButton rbMine;
    @BindView(R.id.rb_meidian)
    RadioButton rbMeidian;
    private MainPagerAdapter adapter;
    private List<Fragment> mListFragment = new ArrayList<>();
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
            .getDefaultAdapter();

    @Override
    protected void onResume() {
        super.onResume();
        upDatatoken();
        autoLogin();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        initPermissioin();
    }


    private void iniCheckUpdata() {
        Map<String, String> map = new HashMap<>();
        map.put("access_token", CommonUtils.getToken(MainActivity.this));
        map.put("version", "" + CommonUtils.getVersionCode(MainActivity.this));
        HttpUtils.postHttp(map, CommonConstant.checkVersion, new HttpUtils.HttpCallBack() {
            @Override
            public void successHttp(final JSONObject jsonObject, int id) {
                if (jsonObject.optInt("code") == 0) {
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("应用更新信息")
                            .setMessage("")
                            .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Uri uri = Uri.parse(jsonObject.optString("data"));
                                    Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                    startActivity(it);
                                }
                            }).show();
                } else {

                }
            }

            @Override
            public void errorHttp(String msg) {

            }
        });
    }

    @Override
    public void initData() {
        CarFragment.isResu = true;
        mListFragment.add(new HomeFragment());
        mListFragment.add(new CarFragment());
        mListFragment.add(new MeiDianFragment());
        mListFragment.add(new MainNearbyFragment());
//        mListFragment.add(new MapFragment());
        mListFragment.add(new MineFragment());
        adapter = new MainPagerAdapter(getSupportFragmentManager(), mListFragment);
        vpContent.setAdapter(adapter);
//        vpContent.setScanScroll(false);
        iniCheckUpdata();
    }

    private void initPermissioin() {
        PermissionUtil permissionUtil = new PermissionUtil(MainActivity.this);
        permissionUtil.requestPermissions();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "取消了", Toast.LENGTH_LONG).show();
            } else {
                String resultMac = result.getContents();
                String str = resultMac.substring(resultMac.lastIndexOf("=") + 1, resultMac.length());
                Log.i("字符串", str + "," + resultMac);
                SharedPreferencesUtils.setParam(MainActivity.this, "ip", "http://" + str);
                toastLong("连接成功!", 0);
                Toast.makeText(this, "连接成功!", Toast.LENGTH_LONG).show();
//                Intent intent = new Intent(this, ControlActivity.class);
//                intent.putExtra("title", str);
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "遥控器");


                intent.putExtra("url", "http://md.93dd.top/index.php/home/index/webremote?mac=" + str + "&tel=" + getPhone() + "&uid=1");
                startActivity(intent);
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @OnClick({R.id.rb_homepage, R.id.rb_shop_car, R.id.rb_meidian, R.id.rb_nearby, R.id.rb_mine})
    public void onClick(View view) {
//        boolean isHome = false;
        String is_login = SharedPreferencesUtils.getParam(MainActivity.this, "is_login", "-1").toString();
        Log.i(TAG, "onClick: " + is_login);
        switch (view.getId()) {
            case R.id.rb_homepage:
                vpContent.setCurrentItem(0);
                initPermissioin();
                break;
            case R.id.rb_shop_car:
                if (!is_login.equals("0")) {
                    new AlertDialog.Builder(this).setTitle("提示").setMessage("请登录").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                } else {
                    vpContent.setCurrentItem(1);
//                    vpContent.setOffscreenPageLimit(3);
                }
                break;
            case R.id.rb_meidian:
//                isHome = true;
                vpContent.setCurrentItem(2);

                if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) {
                    Intent enableBtIntent = new Intent(
                            BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enableBtIntent, 1);
                }
                break;
            case R.id.rb_nearby:
                if (!is_login.equals("0")) {
                    new AlertDialog.Builder(this).setTitle("提示").setMessage("请登录").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                } else {
                    vpContent.setCurrentItem(3);
//                    vpContent.setOffscreenPageLimit(3);
                }
                break;
            case R.id.rb_mine:
                if (!is_login.equals("0")) {
                    new AlertDialog.Builder(this).setTitle("提示").setMessage("请登录").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
                } else {
                    vpContent.setCurrentItem(4);
                }
                break;
        }

//        if (isHome) {
//        rbHomepage.setChecked(false);
//        rbShopCar.setChecked(false);
//        rbNearby.setChecked(false);
//        rbMine.setChecked(false);
//        } else {
//            rbMeidian.setChecked(isHome);
//        }
    }

    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}